package commons;

/**
 * This is main class being which is called when the user clicks on tan button
 */
public class CalculatorAshish {
	/**
	 * This is main function which is called when the user clicks on tan button
	 */
	public Double tanFunc(String str) {

		/** Parsing the given input and converting into a double variable **/
		double i2 = Double.parseDouble(str);
		double i = 0;

		/**
		 * check if the given input is less then 0 then send the input to
		 * calculation function
		 **/

		if (0 <= i2) {

			i = calculatetan(i2);
		}

		/** Return the output being sent by calculation function **/
		return i;
	}

	public static double calculatetan(double deg) {
		double x = 0;

		/** Check if the given input is degree or radians **/
		if (GUI.degButton.isSelected() == true) {

			/**
			 * Use periodicity Check if the input value is greater than 180
			 * degress
			 **/

			if (deg > 180) {
				/**
				 * make the degree value less than 180 to make the calculation
				 * easy
				 **/
				int i = (int) (deg / 180);
				deg = deg - (180.0 * i);
			}
			if (deg < 180.0) {

				/** Use symmetry: check If input is in quadrant 1 **/
				if (deg <= 90.0) {

					/**
					 * Use the cofunction: check If input is less than 45
					 * degrees
					 **/
					if (deg <= 45.0)
						/**
						 * call actual function to calculate tan value using
						 * taylor series
						 **/
						x = actual(deg);
					else

						/**
						 * make the degree value less than 45 by subtracting it
						 * by 90
						 **/
						x = 1 / actual(90.0 - deg);
				}
				if (deg > 90) {

					/**
					 * make the degree value less than 90 by subtracting it by
					 * 180
					 **/
					x = -actual(180.0 - deg);
				}
			}
		} else {

			/**
			 * If the given input is in radians then call tan function to
			 * calculate and return the output
			 **/

			x = tan(deg);
		}

		return x;

	}

	/** This function is used to calculate tan value **/

	public static double tan(double deg) {

		double rad;
		rad = (deg * Math.PI) / 180.0;

		/** Applying Taylor series to get the tan value of the given input **/
		double tan = rad
				+ (pow(rad, 3) / 3)
				+ (2 * (pow(rad, 5) / 15))
				+ (17 * (pow(rad, 7) / 315))
				+ (62 * (pow(rad, 9) / 2835) + (1382 * (pow(rad, 11) / 155925)));
		return tan;
	}

	/** This function is used to calcualte power of any value **/
	public static double pow(double rad, int num) {
		int i;
		double result = 1.0;
		for (i = 0; i < num; i++) {
			result = result * rad;
		}
		;
		return result;
	}

	/**
	 * This function is used to get the tan value by decreasing it to come under
	 * first quadrant
	 **/
	public static double actual(double deg) {
		double tan = 0.0;
		if (deg <= 22.5)
			tan = tan(deg);
		else
			tan = 2 * (tan(deg / 2) / (1 - (tan(deg / 2) * tan(deg / 2))));
		return tan;
	}

}
